package com.bocloud.cmp.service.resource;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.dao.CloudVendorDao;
import com.bocloud.cmp.dao.PortDao;
import com.bocloud.cmp.driver.providers.intf.PortProvider;
import com.bocloud.cmp.entity.resource.CloudVendor;
import com.bocloud.cmp.entity.resource.Port;
import com.bocloud.cmp.interfaces.resource.PortService;
import com.bocloud.cmp.model.PortModel;
import com.bocloud.common.model.BsmResult;
import com.bocloud.common.model.GridBean;
import com.bocloud.common.model.Param;
import com.bocloud.common.model.SimpleBean;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.GridHelper;
import com.bocloud.common.utils.JSONTools;
import com.bocloud.common.utils.MapTools;
import com.bocloud.coordinator.harmony.HarmonyLock;
import com.bocloud.coordinator.harmony.LockFactory;
import com.google.common.collect.Maps;

/**
 * 端口Service接口实现
 * 
 * @author dongkai
 *
 */
@Service("portService")
public class PortServiceImpl implements PortService {

	private static Logger logger = LoggerFactory.getLogger(PortServiceImpl.class);
	@Autowired
	private PortDao portDao;
	@Autowired
	private CloudVendorDao cloudVendorDao;
	@Autowired
	private PortProvider portProvider;
	@Autowired
	private LockFactory lockFactory;

	@Override
	public BsmResult list(int page, int rows, List<Param> params, Map<String, String> sorter, Boolean simple) {
		List<Port> list = null;
		List<SimpleBean> beans = null;
		int total = 0;
		GridBean gridBean = null;
		try {
			if (null == sorter) {
				sorter = Maps.newHashMap();
			}
			sorter.put("id", Common.ONE);
			total = portDao.count(params);
			if (simple) {
				beans = portDao.list(params, sorter);
				gridBean = new GridBean(1, 1, total, beans);
			} else {
				list = this.portDao.list(page, rows, params, sorter);
				gridBean = GridHelper.getBean(page, rows, total, list);
			}
			return new BsmResult(true, gridBean, "查询成功");
		} catch (Exception e) {
			logger.error("list port fail:", e);
			return new BsmResult(false, "查询失败", null, null);
		}
	}

	@Override
	public BsmResult create(String params) {
		JSONObject object = JSONTools.isJSONObj(params);
		Long id = object.getLong(Common.ID);
		String name = object.getString(Common.NAME);
		String networkId = object.getString("networkId");
		try {
			CloudVendor cloudVendor = cloudVendorDao.query(id);
			if (null == cloudVendor) {
				logger.error("get cloudVendor failure!");
				return new BsmResult(false, "创建失败!");
			}
			Map<String, Object> param = MapTools.simpleMap("name", name);
			param.put("networkId", networkId);
			PortModel portModel = JSONObject.parseObject(JSONObject.toJSONString(param), PortModel.class);
			BsmResult bsmResult = portProvider.create(cloudVendor.getUuid(), null, portModel);
			if (null == bsmResult || bsmResult.isFailed()) {
				return new BsmResult(false, "创建失败!");
			}
			Port port = JSONObject.parseObject(JSONObject.toJSONString(bsmResult.getData()), Port.class);
			port.setVendorId(id);
			portDao.save(port);
			return new BsmResult(true, "创建成功!");
		} catch (Exception e) {
			logger.error("create port failure:", e);
			return new BsmResult(false, "创建失败!");
		}
	}

	@Override
	public BsmResult remove(Long id) {
		String path = Port.class.getSimpleName() + "_" + id;
		HarmonyLock lock = null;
		Boolean result = false;
		try {
			lock = lockFactory.getLock(path);
			if (!lock.acquire(path, 10, TimeUnit.SECONDS)) {
				logger.warn("Get harmonyLock time out!");
				return new BsmResult(false, "请求超时", "", "");
			}
			Port port = portDao.query(id);
			if (null == port) {
				logger.warn("port data not exist");
				return new BsmResult(false, "数据不存在", "", "");
			}
			// 云供应商
			CloudVendor cloudVendor = cloudVendorDao.query(port.getVendorId());
			if (null == cloudVendor) {
				logger.error("get cloudVendor failure");
				return new BsmResult(false, "删除失败", "", "");
			}
			BsmResult bsmResult = portProvider.remove(port.getPortId(), cloudVendor.getUuid(), "");
			if (null == bsmResult || !bsmResult.isSuccess()) {
				return new BsmResult(false, "删除失败");
			}
			result = portDao.delete(id);
		} catch (Exception e) {
			logger.error("remove port fail:", e);
			return new BsmResult(false, "删除失败", "", "");
		} finally {
			if (null != lock) {
				lock.release();
			}
		}
		return result ? new BsmResult(true, "删除成功") : new BsmResult(false, "删除失败", "", "");
	}

	@Override
	public BsmResult detail(Long id) {
		try {
			Port port = portDao.query(id);
			return new BsmResult(true, port, "查询成功!");
		} catch (Exception e) {
			logger.error("query port detail failure:", e);
			return new BsmResult(false, "查询详情失败!");
		}
	}

}
